package com.ruicar.afs.cloud.apply.pre.loan.controller;

import com.alibaba.fastjson.JSONArray;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.ruicar.afs.cloud.apply.common.entity.ApplyContractInfo;
import com.ruicar.afs.cloud.apply.common.entity.ApplyOprRecord;
import com.ruicar.afs.cloud.apply.common.utils.ApplyConstants;
import com.ruicar.afs.cloud.apply.contract.service.ContractMngService;
import com.ruicar.afs.cloud.apply.pre.loan.condition.ContractMngCondition;
import com.ruicar.afs.cloud.apply.pre.loan.condition.OrderOprCondition;
import com.ruicar.afs.cloud.apply.pre.loan.service.ApplyOprRecordService;
import com.ruicar.afs.cloud.apply.pre.loan.vo.ContractMngLoanAppVO;
import com.ruicar.afs.cloud.bizcommon.business.entity.FinCostDetails;
import com.ruicar.afs.cloud.bizcommon.business.service.ApplyCostDetailsService;
import com.ruicar.afs.cloud.common.core.query.QueryCondition;
import com.ruicar.afs.cloud.common.core.security.util.SecurityUtils;
import com.ruicar.afs.cloud.common.core.util.IResponse;
import com.ruicar.afs.cloud.parameter.commom.enums.OrderOprType;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.cache.annotation.CacheEvict;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * 订单管理-放款申请
 *
 * @author :jihuigeng
 * @date :2020-05-25
 */
@RestController
@AllArgsConstructor
@Slf4j
@RequestMapping("/contractMng")
public class ContractMngController {

    private final ContractMngService contractMngService;
    private final ApplyOprRecordService oprRecordService;
    private final ApplyCostDetailsService applyCostDetailsService;

    /**
     * 放款申请-多条件查询
     *
     * @return
     */
    @ApiOperation("放款申请-多条件查询")
    @PostMapping("/getMngLoanOrderInfo")
    public IResponse<List<ContractMngLoanAppVO>> getMngLoanOrderInfo(@RequestBody QueryCondition<ContractMngCondition> condition) {
        JSONArray roleArray = SecurityUtils.getUser().getUserExtInfo().getJSONArray("roles");
        if(roleArray != null){
             if(roleArray.toString().indexOf(ApplyConstants.ROLE_ADMIN) > -1){
                 return IResponse.success(null);
             }else{
                 Page page = new Page(condition.getPageNumber(), condition.getPageSize());
                 IPage<ContractMngLoanAppVO> loanOrderInfoList = this.contractMngService.getMngLoanOrderInfo(condition.getCondition(), page);
                 List<ContractMngLoanAppVO> records = loanOrderInfoList.getRecords();
                 for(ContractMngLoanAppVO contractMngLoanAppVO:records){
                     BigDecimal money=BigDecimal.ZERO;
                     List<FinCostDetails> finCostDetailsList=applyCostDetailsService.getCostDetailsList(contractMngLoanAppVO.getApplyNo());
                     for(FinCostDetails finCostDetails:finCostDetailsList){
                         money=money.add(finCostDetails.getLoanAmt()==null?BigDecimal.ZERO:finCostDetails.getLoanAmt());
                     }
                     contractMngLoanAppVO.setLoanAmt(money);
                 }
                 return IResponse.success(loanOrderInfoList);
             }
        }else{
            return IResponse.fail("此账号未配置权限,请检查账号！");
        }
    }

    /**
     * 放款申请-撤回
     *
     * @param condition
     * @return
     */
    @ApiOperation("放款申请-撤回")
    @PostMapping("/saveBack")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "apply_opr_record", allEntries = true)
    public IResponse saveBack(@ModelAttribute OrderOprCondition condition) {
        //操作记录表更新-操作类型-操作人-操作时间-申请编号-理由
        ApplyOprRecord oprRecord = new ApplyOprRecord();
        //申请编号
        oprRecord.setApplyNo(condition.getApplyNo());
        //操作类型：撤回
        oprRecord.setApplyType(OrderOprType.BACK);
        //撤回理由
        oprRecord.setApplyReason(condition.getBackReason());
        //操作时间
        oprRecord.setCreateTime(new Date());
        //当前操作人
        oprRecord.setCreateBy(SecurityUtils.getUsername());
        //保存撤回记录
        oprRecordService.save(oprRecord);
        /*
        调用工作流撤回接口，待处理 todo
         */
        ApplyContractInfo contractInfo = contractMngService.getContractInfo(condition);
        if (contractInfo != null) {
            //更新合同状态为已退回状态
            contractInfo.setContractStatus(ApplyConstants.CONTRACT_STATUS_BACK);
            //更新时间
            contractInfo.setUpdateTime(new Date());
            //更新人
            condition.setUpdateBy(SecurityUtils.getUsername());
            //更新
            contractMngService.updateContractInfo(contractInfo);
        }
        return IResponse.success(Boolean.TRUE);
    }

    //取消

    @ApiOperation("放款申请-取消")
    @PostMapping("/saveCancel")
    @Transactional(rollbackFor = Exception.class)
    @CacheEvict(value = "apply_opr_record", allEntries = true)
    public IResponse saveCancel(@ModelAttribute OrderOprCondition condition) {

        //操作记录表更新-操作类型-操作人-操作时间-申请编号-理由
        ApplyOprRecord oprRecord = new ApplyOprRecord();
        //申请编号
        oprRecord.setApplyNo(condition.getApplyNo());
        //操作类型:取消
        oprRecord.setApplyType(OrderOprType.CANCEL);
        //操作时间
        oprRecord.setCreateTime(new Date());
        //当前操作人
        oprRecord.setCreateBy(SecurityUtils.getUsername());
        //保存取消记录
        oprRecordService.save(oprRecord);
          /*
        调用工作流取消接口，待处理 todo
         */
        ApplyContractInfo contractInfo = contractMngService.getContractInfo(condition);
        if (contractInfo != null) {
            //更新合同状态为取消
            contractInfo.setContractStatus(ApplyConstants.CONTRACT_STATUS_CANCEL);
            contractInfo.setUpdateTime(new Date());
            contractInfo.setUpdateBy(SecurityUtils.getUsername());
            contractMngService.updateContractInfo(contractInfo);
        }
        return IResponse.success(Boolean.TRUE);
    }
    //转单
    /**
     * 转给同级或者上级。。。。。。
     */
}
